package org.uugu.counter.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import org.uugu.counter.R;
import org.uugu.counter.Support.CommonParam;
import org.uugu.counter.Support.DatabaseUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends Activity {


    private DatabaseUtils dbUtil;

    private Button button;

    private GridView gridView;

    private int dataId;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // 打开SQLite DB文件
        dbUtil = new DatabaseUtils(this, CommonParam.DB_NAME, CommonParam.VERSION);
        gridView = (GridView)findViewById(R.id.gridView);

        freshGridView();

        button = (Button)findViewById(R.id.button);

        // 绑定按钮监听事件
        button.setOnClickListener(new ButtonListener());
        gridView.setOnItemClickListener(new GridViewItemClickListener());
        gridView.setOnItemLongClickListener(new GridViewItemLongClickListener());

    }

    /**
     * 刷新当前页面数据
     */
    private void freshGridView() {
        Cursor cursor = dbUtil.getReadableDatabase().rawQuery("select * from groups", null);
        List<Map<String, String>> searchResult = dbUtil.converCursorToList(cursor);
        SimpleAdapter sa = new SimpleAdapter(this, searchResult, R.layout.cell,
                new String[]{"id", "name", "date"},
                new int[]{R.id.textView, R.id.textView2, R.id.textView3});
        gridView.setAdapter(sa);
    }

    class ButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AddGroupActivity.class);
            startActivity(intent);
        }
    }

    class GridViewItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HashMap<String, Object> item=(HashMap<String, Object>) parent.getItemAtPosition(position);
            Bundle data = new Bundle();
            Intent intent = new Intent(MainActivity.this, WorkActivity.class);
            data.putInt("id", Integer.valueOf(item.get("id").toString()));
            data.putString("groupName", item.get("name").toString());
            intent.putExtras(data);

            startActivity(intent);
        }
    }

    class GridViewItemLongClickListener implements AdapterView.OnItemLongClickListener{


        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HashMap<String, Object> item=(HashMap<String, Object>) parent.getItemAtPosition(position);
            Bundle data = new Bundle();
            Intent intent = new Intent(MainActivity.this, WorkActivity.class);
            data.putInt("id", Integer.valueOf(item.get("id").toString()));
            data.putString("groupName", item.get("name").toString());
            intent.putExtras(data);

            startActivity(intent);
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            HashMap<String, Object> item=(HashMap<String, Object>) parent.getItemAtPosition(position);
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this).setTitle("确认删除")
                    .setMessage("确认删除ID为" + item.get("id") + "的该组数据吗？");
            dataId = Integer.valueOf(item.get("id").toString());
            setPositiveButton(builder);
            setNegativeButton(builder).create().show();
            return true;
        }

        private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder){
            return builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dbUtil.getWritableDatabase().delete("groups", "id = ?", new String[]{String.valueOf(dataId)});
                    dbUtil.getWritableDatabase().delete("data", "group_id = ?", new String[]{String.valueOf(dataId)});
                    Toast toast = Toast.makeText(MainActivity.this, "已删除该组数据，组号："+dataId, Toast.LENGTH_SHORT);
                    toast.show();
                    // 刷新页面数据
                    freshGridView();
                }
            });
        }

        private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder){
            return builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
        }
    }
    /**
     * 清空数据功能
     * @param dbUtil
     */
    public static void clearData(DatabaseUtils dbUtil) {
            dbUtil.clearTable(dbUtil.getWritableDatabase());
    }

    // 清除数据菜单ID
    final int CLEAR_DATA = 0x110;
    // 退出菜单ID
    final int EXIT = 0x111;
    // 刷新按钮数据ID
    final int FRESH = 0x109;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, FRESH, 0, "刷新");
        menu.add(0, CLEAR_DATA, 1, "清空数据");
        menu.add(0, EXIT, 2, "退出");
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 选择菜单相应功能执行
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case FRESH:
                freshGridView();
                break;
            case CLEAR_DATA:
                clearData(dbUtil);
                Toast toast = Toast.makeText(MainActivity.this, "数据已清空，刷新后起效！", Toast.LENGTH_SHORT);
                toast.show();
                break;
            case EXIT:
                System.exit(0);
                break;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(dbUtil != null){
            dbUtil.close();
        }
    }
}
